package team;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;


/**
 * User Interface for part modification
 * 
 * @author Sean Peng
 *
 */
public class PartModFrame extends JFrame{
	
	private JFrame frame = this;
	
	private DefaultListModel<String> vendorListModel;
	private DefaultListModel<String> partListModel;
	private JTable partInfoTable;
	private String vendor;
	private String partNum;

	public PartModFrame(final JFrame initialFrame) {
		
		vendorListModel = new DefaultListModel<String>();
		partListModel = new DefaultListModel<String>();
		partInfoTable = new JTable() {
			
			public boolean isCellEditable(int rowIndex, int colIndex) {
				
				if(colIndex == 0)
					return false;
				
				return true;
			}
		};
		
		JButton backButton = new JButton("Back");
		JButton addButton = new JButton("Add Part");
		final JButton updateButton = new JButton("Update");
		final JButton deleteButton = new JButton("Delete");
		
		updateButton.setEnabled(false);
		deleteButton.setEnabled(false);
		
		backButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				
				initialFrame.setVisible(true);
				frame.dispose();
			}
		
		});
		
		addButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				
				AddNewPartFrame addPart = new AddNewPartFrame(frame);
				frame.setVisible(false);
			}
			
		});
		
		updateButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				
				if(inputValidator()) {
					
					int rowCount = partInfoTable.getModel().getRowCount();
					ArrayList<String> inputData = new ArrayList<String>();
					
					for(int i=0; i<rowCount; i++) {
						
						if(partInfoTable.getModel().getValueAt(i, 1) == null)
							inputData.add( "" );
						else
							inputData.add( partInfoTable.getModel().getValueAt(i, 1).toString().toUpperCase() );
					}
					
					if(Result.checkExisting(vendor, inputData.get(0))) {
						Result.updatePart(vendor, partNum, inputData);
					}
					else {
						Result.insertNewPart(vendor, inputData);
						Result.updateRADCRX(vendor, inputData.get(0), partNum);
					}
				}
				else
					JOptionPane.showMessageDialog(null, "Invalid Input", "Error", JOptionPane.ERROR_MESSAGE);							
			}
			
		});
		
		deleteButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				
				Result.deletePart(vendor, partNum);
				
				partListModel.clear();
				updateButton.setEnabled(false);
				deleteButton.setEnabled(false);
				
				String[] parts = Result.getPartNumber(vendor);
				for(String part : parts)
					partListModel.addElement(part);
				
				String[] dummy = {""};
				constructDescriptionTable(vendor, dummy);
			}
			
		});
		
		String[] vendors = Result.getVendor();
		
		for(String v : vendors)
			vendorListModel.addElement(v);
		
		JList<String> vendorList = new JList<String>(vendorListModel);			
		vendorList.setBorder(BorderFactory.createTitledBorder("Available Vendor:"));
		vendorList.addListSelectionListener(new ListSelectionListener() {

			@Override
			public void valueChanged(ListSelectionEvent e) {
				
				//only fire up when mouse up
				if(!e.getValueIsAdjusting()) {
					
					@SuppressWarnings("unchecked")
					JList<String> list = (JList<String>)e.getSource();
					vendor = list.getSelectedValue();
					partListModel.clear();
					updateButton.setEnabled(false);
					deleteButton.setEnabled(false);
					
					String[] parts = Result.getPartNumber(vendor);
					for(String part : parts)
						partListModel.addElement(part);
				}
			}		
		});
		
		JList<String> partList = new JList<String>(partListModel);		
		partList.setBorder(BorderFactory.createTitledBorder("Available Part:"));
		partList.addListSelectionListener(new ListSelectionListener() {

			@Override
			public void valueChanged(ListSelectionEvent e) {
				
				//only fire up when mouse up
				if(!e.getValueIsAdjusting() && ((JList<String>)e.getSource()).getModel().getSize() != 0) {
					
					@SuppressWarnings("unchecked")
					JList<String> list = (JList<String>)e.getSource();
					partNum = list.getSelectedValue();
					
					try {
						Integer.parseInt(partNum);
						
						String[] spec = Result.getPartSpec(vendor, partNum);
						constructDescriptionTable(vendor, spec);
						
						updateButton.setEnabled(true);
						deleteButton.setEnabled(true);
						
					} catch (Exception ex) {
						System.err.println(ex.getMessage());
					}
				}
			}
			
		});
		
		JScrollPane vendorScroll = new JScrollPane(vendorList);
		JScrollPane partScroll = new JScrollPane(partList);
		JScrollPane specScroll = new JScrollPane(partInfoTable);
		
		vendorScroll.setPreferredSize(new Dimension(150, 115));
		partScroll.setPreferredSize(new Dimension(150, 115));
		specScroll.setPreferredSize(new Dimension(500, 115));
		
		specScroll.setBorder(BorderFactory.createTitledBorder("Part Description: "));
		
		JPanel partSelection = new JPanel();
		partSelection.add(vendorScroll, BorderLayout.WEST);
		partSelection.add(partScroll, BorderLayout.EAST);
		
		JPanel buttonPanel = new JPanel();
		buttonPanel.add(addButton);
		buttonPanel.add(updateButton);
		buttonPanel.add(deleteButton);
		buttonPanel.add(backButton);
		
		this.setSize(600,400);
		this.setTitle("Part Modification");
		this.add(partSelection, BorderLayout.NORTH);
		this.add(specScroll, BorderLayout.CENTER);
		this.add(buttonPanel, BorderLayout.SOUTH);
		this.setLocationRelativeTo(null);
		this.setVisible(true);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	} //End of Constructor
	
	
	/**
	 * Construct a table to display part information
	 * @param vendor name for the vendor's table
	 * @param data part information data
	 */
	private void constructDescriptionTable(String vendor, String[] data) {		 
		
		DefaultTableModel partInfoModel = (DefaultTableModel) partInfoTable.getModel();
		
		//clear the existing table
		partInfoModel.setColumnCount(0);
		partInfoModel.addColumn("Part", Result.getColumnName(vendor));	
		partInfoModel.addColumn("Spec", data);
		partInfoModel.fireTableDataChanged();
		
	}
	
	

	private boolean inputValidator() {
		
		try {
			//P_NUMBER
			Double.parseDouble( partInfoTable.getModel().getValueAt(0, 1).toString() );
			
			//PRICE
			Double.parseDouble( partInfoTable.getModel().getValueAt(8, 1).toString() );
			
			//AMOUNT
			Integer.parseInt( partInfoTable.getModel().getValueAt(9, 1).toString() );
			
		} catch(NumberFormatException e) {
			return false;
		}
		
		return true;
	}

}
